<script lang="ts" setup>
	import dayjs from '#build/dayjs.imports.mjs'
	import { getUrlByFileNo } from '~/api/file'
	import { getCategoryList, getExpertWorkInfo, getHealthSX, getkpzlList, getPrizeWinningdata } from '~/api/home'

	const title = ref('科普资料')
	const routePath = [{ name: '首页', path: '/' }, { name: title }]
	const timeNow = ref('')
	const total = ref(0)
	const infoType = ref('All')
	const valuedate = ref()
	const timeYS = ref('background: linear-gradient(159.97deg, rgba(206,234,158,1) -140.78%,rgba(53,179,137,1) 89.45%);color:#fff')
	const timeNo = ref('background:none;color:#333;border:1px solid rgba(229,229,234,1);')
	const infocss = ref('background:linear-gradient(88.92deg, rgba(92,224,168,0.41) 1.07%,rgba(195,228,214,0.22) 99.94%);padding-left:10px')
	let queryParams = reactive<{
		page : {
			rownumber : number
			pageNo : number
		}
		condition ?: any[]
		positions ?: string
	}>(
		{
			page: {
				rownumber: 8,
				pageNo: 1,
			},
			positions: '首页',
		},
	)

	function clickTime(item : string) {
		timeNow.value = item
		const res = getTimePeriod(item)
		let indextime
		if (queryParams.condition) {
			indextime = queryParams.condition.findIndex(item => item.colName === 'release_time')

			if (indextime >= 0) {
				const lefindex = queryParams.condition.findIndex(item => item.colName === 'release_time' && item.ruleType === 'le')
				const rigindex = queryParams.condition.findIndex(item => item.colName === 'release_time' && item.ruleType === 'ge')
				if (res?.start && res?.end) {
					valuedate.value = [res.start, res.end]
					queryParams.condition[rigindex].value = valuedate.value[0]
					queryParams.condition[lefindex].value = valuedate.value[1]
					getPopularScienceMaterialsData()
				}
				else {
					queryParams.condition = queryParams.condition.filter(item => item.colName !== 'release_time')
					getPopularScienceMaterialsData()
				}
			}
			else {
				if (res?.start && res?.end) {
					valuedate.value = [res.start, res.end]
          const condition = []
					condition.push(
						{
							colName: 'release_time',
							value: valuedate.value[0],
							ruleType: 'le',
						},
					)
					condition.push(
						{
							colName: 'release_time',
							value: valuedate.value[1],
							ruleType: 'ge',
						},
					)
					getPopularScienceMaterialsData(condition)
				}
				else {
					queryParams.condition = queryParams.condition.filter(item => item.colName !== 'release_time')
					getPopularScienceMaterialsData()
				}
			}
		}
		else {
			if (res?.start && res?.end) {
				valuedate.value = [res.start, res.end]
				const condition = [{
					colName: 'release_time',
					value: valuedate.value?.length ? valuedate.value[1] : null,
					ruleType: 'le',
				}, {
					colName: 'release_time',
					value: valuedate.value?.length ? valuedate.value[0] : null,
					ruleType: 'ge',
				}]
			  getPopularScienceMaterialsData(condition)
			}
		}
	}
	function getTimePeriod(periodType : string | undefined) {
		if (periodType) {
			const currentDate = new Date()
			switch (periodType) {
				case '1':
					{ const oneWeekAgo = new Date(currentDate)
					oneWeekAgo.setDate(currentDate.getDate() - 7)
					return { start: dayjs(oneWeekAgo).format('YYYY-MM-DD'), end: dayjs(currentDate).format("YYYY-MM-DD") } }
				case '2':
					{ const oneMonthAgo = new Date(currentDate)
					oneMonthAgo.setMonth(currentDate.getMonth() - 1)
					return { start: dayjs(oneMonthAgo).format("YYYY-MM-DD"), end: dayjs(currentDate).format("YYYY-MM-DD") } }
				case '3':
					{ const sixMonthsAgo = new Date(currentDate)
					sixMonthsAgo.setMonth(currentDate.getMonth() - 6)
					return { start: dayjs(sixMonthsAgo).format("YYYY-MM-DD"), end: dayjs(currentDate).format("YYYY-MM-DD") } }
				case '4':
					if (valuedate.value)
						return { start:dayjs(valuedate.value[0]).format("YYYY-MM-DD"), end:  dayjs(valuedate.value[1]).format("YYYY-MM-DD")  }
					else return { start: '', end: '' }
				default:
					throw new Error('Invalid period type. Choose from "week", "month", or "sixMonths"')
			}
		}
	}
	const keyType = ref('')
	const name = ref('科普资料/科普资源/')
	function keyTypeClisk(item : string) {
    console.log(item);
    
		keyType.value = item
    queryParams.page.pageNo = 1
		if (queryParams.condition) {
			const index = queryParams.condition.findIndex(item1 => item1.colName === 'classify_name')
			if (index >= 0) {
				queryParams.condition[index].value = name.value + keyType.value
			}
			else {
				queryParams.condition.push({
					colName: 'classify_name',
					value: name.value + keyType.value,
					ruleType: 'like]',
				})
			}
		}
		else {
			queryParams.condition = []
			queryParams.condition.push({
				colName: 'classify_name',
				value: name.value + keyType.value,
				ruleType: 'like]',
			})

		}
    const condition = [
      ...queryParams.condition
    ]
		getPopularScienceMaterialsData(condition)
	}
	function keyTypeClickAreaLeval(item : string, type : string) {
		if (keyType.value === item) {
			item = ''
		}
		keyType.value = item
    queryParams.page.pageNo = 1
		if (type === '2' && item === '其他作品') {
			queryParams.condition = [{
				colName: 'classify_name',
				value: `科普资料/专家作品`,
				ruleType: 'like]',
			}]
			return getExpertwork()
		}
		let queryValue = `科普资料/${type === '1' ? '获奖作品' : '专家作品'}`
		if (keyType.value) {
			queryValue += `/${keyType.value}`
		}

		if (queryParams.condition) {
			const index = queryParams.condition.findIndex(item1 => item1.colName === 'classify_name')
			if (index >= 0) {
				queryParams.condition[index].value = queryValue
			}
			else {
				queryParams.condition.push({
					colName: 'classify_name',
					value: queryValue,
					ruleType: 'like]',
				})
			}
		}
		else {
			queryParams.condition = [{
				colName: 'classify_name',
				value: queryValue,
				ruleType: 'like]',
			}]
		}
		if (type === '1') {
			getAwardWinningworksData()
		}
		if (type === '2') {
			getExpertwork()
		}
	}
	const PopularScienceMaterials = ref<any[]>([])
	const AwardWinningworks = ref<any[]>([])
	const eyes = ref('/img/eys.png')
	// 分页参数更改
	function onPageChange(params : { pageNum : number, pageSize : number }) {
		queryParams.page.pageNo = params.pageNum
		// queryParams.pageSize = params.pageSize
		//   getList()
	}
	// 分页参数更改
	function onPageChangeKPZL(params : { pageNum : number, pageSize : number }) {
		queryParams.page.pageNo = params.pageNum
		// queryParams.pageSize = params.pageSize
		getPopularScienceMaterialsData()
	}
	// 分页参数更改
	function onPageChangeHJZP(params : { pageNum : number, pageSize : number }) {
		queryParams.page.pageNo = params.pageNum
		// queryParams.pageSize = params.pageSize
		//   getList()
		getAwardWinningworksData()
	}
	function typeClick(item : string) {
		infoType.value = item
		if (queryParams.condition) {
			queryParams = {
				page: {
					rownumber: 8,
					pageNo: 1,
				},
			}
		}
		if (infoType.value?.includes('资源')) {
			getPopularScienceMaterialsData()
		}
		else if (infoType.value === '获奖作品') {
			getAwardWinningworksData()
		}
		else if (infoType.value === '专家作品') {
			getExpertwork()
		}
		getSiderdata()
	}
	const ExpertworkList = ref<any[]>([])
	async function getExpertwork() {
		try {
			const res = await getExpertWorkInfo(queryParams)
			if (res.state === 'SUCCESS') {
				ExpertworkList.value = res.data
				total.value = res.page.total
			}
		}
		catch (error) {
			console.error(error)
		}
	}
	async function getPopularScienceMaterialsData(condition?:any) {
		let tempParams = JSON.parse(JSON.stringify(queryParams))
		tempParams.condition = [{
			colName: "classify_name",
			value: '科普资料/科普资源',
			ruleType: "like]"
		}]
    if(Array.isArray(condition) && condition.length){
      tempParams.condition.push(...condition)
    }
    if(keyType.value){
      tempParams.condition.push({
					colName: 'classify_name',
					value: name.value + keyType.value,
					ruleType: 'like]',
				})
    }
   
		try {
			const res = await getkpzlList(tempParams)
			PopularScienceMaterials.value = res.data
			total.value = res.page.total
		}
		catch (error) {
			console.error(error)
		}
	}
	async function getAwardWinningworksData() {
		try {
			const res1 = await getPrizeWinningdata(queryParams)
			AwardWinningworks.value = res1.data
			total.value = res1.page.total
		}
		catch (error) {
			console.error(error)
		}
	}
	const router = useRouter()
	function toDetail(item : any, type : any) {
		router.push({ path: `/peopleHealth/popularizationDetail/${item}&${type}` })
	}

	const siderData = ref()
	async function getSiderdata() {
		const paramss = {
			page: {
				rownumber: 3,
				pageNo: 1,
			},
			condition: [{
				colName: 'column_recommendation',
				ruleType: 'eq',
				value: '是',
			}],
			order: [{
				colName: 'release_time',
				orderType: 'desc', // asc升序 desc降序
			}],

			positions: '首页',
		}
		let res2

		if (infoType.value === 'All') {
			res2 = await getkpzlList(paramss)
		}
		else {
			if (infoType.value?.includes('资源')) {
				res2 = await getkpzlList(paramss)
			}
			else if (infoType.value === '获奖作品') {
				res2 = await getPrizeWinningdata(paramss)
			}
			else if (infoType.value === '专家作品') {
				res2 = await getExpertWorkInfo(paramss)
			}
		}
		siderData.value = res2.data
	}
	async function backInit() {
		location.reload()
	}

	const typeList = ref([])

	onMounted(async () => {
		getPopularScienceMaterialsData()
		getAwardWinningworksData()
		getExpertwork()
		getSiderdata()
		const res = await getCategoryList({
			condition: [{
				colName: 'path_name',
				ruleType: 'like]',
				value: '科普资料%',
			}],
		})
		typeList.value = res.data[0].children
	})

	const listAll = computed(() => {
		return [
			{
				type: '科普资源',
				list: PopularScienceMaterials.value,
			},
			{
				type: '获奖作品',
				list: AwardWinningworks.value,
			},
			{
				type: '专家作品',
				list: ExpertworkList.value,
			},
		]
	})

	function getImageAddress(url : string) {
		if (url?.indexOf('http') === 0) {
			return compressImage(url)
		}
		else if (url) {
			return getUrlByFileNo(url)
		}
		return '/img/kpzl.png'
	}
</script>

<template>
	<div>
		<PublicSearch type="科普资料" />
		<PublicSearchDialog type="科普资料" />
		<div class="pb-80px">
			<div class="bg-#fff">
				<CommonPageContainer :title="title" :path="routePath">
					<div class="mt-20px flex justify-between">
						<div v-if="infoType === 'more'" class="w-85%">
							<PublicList />
							<PublicPagination :page-size="queryParams.page.rownumber"
								:page-num="queryParams.page.pageNo" :total="total" @change="onPageChange" />
						</div>
						<div v-show="infoType === 'All'" class="w-85%">
							<div v-for="data in listAll" :key="data.type" class="mt-20px w-95%">
								<div class="h-40px w-100% flex justify-between">
									<div class="datas-center flex items-center">
										<span class="ml-10px inline-block h-8px w-8px bg-#0E9472" />
										<span class="pl-4 font-extrabold" text="#016738">{{ data.type }}</span>
									</div>
									<div class="flex cursor-pointer" @click="typeClick(data.type)">
										<div class="h-20px">
											更多
										</div>
										<img class="ml-5px mt-2px h-22px" src="/img/more.png" alt="">
									</div>
								</div>
								<div v-if="data.list && data.list.length"
									grid="~ cols-[repeat(auto-fill,_minmax(200px,_1fr))] gap-10px">
									<div v-for="item in data.list" :key="item.id" class="overflow-hidden rounded-6px"
										border="1px solid #E5E7EB" shadow="hover:sm">
										<el-image v-if="item.cover_file_name" class="h-150px w-100% cursor-pointer"
											fit="cover" lazy :src="getImageAddress(item.cover_file_name)"
											@click="toDetail(item.id, data.type)">
											<template #placeholder>
												<div class="image-slot">
													<i class="i-ri:loader-fill loader" />
												</div>
											</template>
										</el-image>
										<el-image v-else class="h-150px w-100% cursor-pointer" fit="cover"
											src="/img/placeholder.jpg" @click="toDetail(item.id, data.type)" />
										<div class="cursor-pointer truncate p-2 hover:text-green-500"
											@click="toDetail(item.id, data.type)">
											{{ item.title_name }}
										</div>
										<div class="flex items-center justify-between p-2">
											<div>{{ dayjs (item.release_time).format('YYYY-MM-DD') }}</div>
											<!-- <div class="cursor-pointer rounded-sm p-1" text="#35B389 14px" border="1px solid #35B389" >
                        查看详情
                      </div> -->
										</div>
									</div>
								</div>
								<!-- 使用empty代替 -->
								<div v-else>
									<el-empty :image-size="120" />
								</div>
								<!-- <div v-else v-loading="true" class="mt-10px h-200px w-100%" /> -->
							</div>
						</div>
						<div v-if="infoType?.includes('资源')" class="w-85%">
							<div class="flex items-center py-5">
								<div class="h-40px w-40px flex cursor-pointer items-center justify-center rounded-md"
									:style=" timeYS" @click="backInit">
									<div class="h-18px w-18px flex items-center justify-center rounded-50% bg-#fff">
										<span class="flex items-center -ml-2px" text="#0E9472">&lt;</span>
									</div>
								</div>
								<span class="pl-4 font-extrabold" text="#016738">{{ infoType }}</span>
							</div>
							<div class="h-40px flex">
								<div class="cursor-pointer rounded-sm px-8px pt-6px"
									:style="timeNow === '1' ? timeYS : timeNo" @click="clickTime('1')">
									近一周
								</div>
								<div class="mx-10px cursor-pointer rounded-sm px-8px pt-6px"
									:style="timeNow === '2' ? timeYS : timeNo" @click="clickTime('2')">
									近一月
								</div>
								<div class="cursor-pointer rounded-sm px-8px pt-6px"
									:style="timeNow === '3' ? timeYS : timeNo" @click="clickTime('3')">
									近半年
								</div>
								<div class="ml-10px">
									<el-date-picker v-model="valuedate" style="height:100%" type="daterange"
										range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" size="large"
										@change="clickTime('4')" />
								</div>
							</div>
							<div v-if="typeList[0] && typeList[0].children" class="flex">
								<div v-for="item in typeList[0].children" :key="item.id" text="#1D2128 16px"
									class="item-center w-100% flex py-5px">
									<div class="w-60px cursor-pointer pt-2 text-center font-bold font-sans"
										:style="keyType === item.classify_name ? 'border-bottom:5px solid #35B389' : ''"
										@click="keyTypeClisk(item.classify_name)">
										{{ item.classify_name }}
									</div>
								</div>
							</div>
							<div v-if="PopularScienceMaterials.length"
								grid="~ cols-[repeat(auto-fill,_minmax(200px,_1fr))] gap-20px" class="mt-15px">
								<div v-for="item in PopularScienceMaterials" :key="item.id" calss="cursor-pointer"
									@click="toDetail(item.id, '资源')">
									<el-image class="h-200px w-100%" lazy fit="cover"
										:src="getImageAddress(item.cover_file_name)" />
									<div class="bg-#fff p-10px">
										<div class="cursor-pointer truncate hover:text-green-500">
											{{ item.title_name }}
										</div>
										<div class="flex justify-between">
											<span text="#AEAEB2 12px">
												{{ item.release_time.split(' ')[0] }}
											</span>
											<div class="flex">
												<img class="h-18px w-15px" :src="eyes" alt="">
												<span text="#AEAEB2 12px">{{ item.page_view_num }}</span>
											</div>
										</div>
									</div>
								</div>
							</div>
							<div v-else>
								<el-empty :image-size="200" />
							</div>
							<div class="mt-15px w-100% flex justify-end pr-20px">
								<PublicPagination :page-size="queryParams.page.rownumber"
									:page-num="queryParams.page.pageNo" :total="total" @change="onPageChangeKPZL" />
							</div>
						</div>
						<div v-if="infoType === '获奖作品'" class="w-85%">
							<div class="flex items-center py-5">
								<div class="h-40px w-40px flex cursor-pointer items-center justify-center rounded-md"
									:style=" timeYS" @click="backInit">
									<div class="h-18px w-18px flex items-center justify-center rounded-50% bg-#fff">
										<span class="flex items-center -ml-2px" text="#0E9472">&lt;</span>
									</div>
								</div>
								<span class="pl-4 font-extrabold" text="#016738">{{ infoType }}</span>
							</div>
							<div v-if="typeList[1] && typeList[1].children" class="flex">
								<div v-for="item in typeList[1].children" :key="item.uid" text="#1D2128 16px"
									class="item-center w-100PX flex py-5px">
									<div class="w-60px cursor-pointer pt-2 text-center font-bold font-sans"
										:style="keyType === item.classify_name ? 'border-bottom:5px solid #35B389' : ''"
										@click="keyTypeClickAreaLeval(item.classify_name, '1')">
										{{ item.classify_name }}
									</div>
								</div>
							</div>
							<div v-if="AwardWinningworks.length" class="mt-15px"
								grid="~ cols-[repeat(auto-fill,_minmax(200px,_1fr))] gap-10px">
								<div v-for="item in AwardWinningworks" :key="item.id" calss="cursor-pointer"
									@click="toDetail(item.id, '获奖作品')">
									<el-image class="h-200px w-100%" lazy fit="cover"
										:src="getImageAddress(item.cover_file_name)" alt="" />
									<div class="bg-#fff p-10px">
										<div class="cursor-pointer truncate hover:text-green-500">
											{{ item.title_name }}
										</div>
										<div class="flex justify-between">
											<span text="#AEAEB2 12px">
												{{ item.release_time.split(' ')[0] }}
											</span>
											<div class="flex">
												<img class="h-18px w-15px" :src="eyes" alt="">
												<span text="#AEAEB2 12px">{{ item.page_view_num }}</span>
											</div>
										</div>
									</div>
								</div>
							</div>
							<div v-else>
								<el-empty :image-size="200" />
							</div>
							<div class="mt-15px w-100% flex justify-end pr-20px">
								<PublicPagination :page-size="queryParams.page.rownumber"
									:page-num="queryParams.page.pageNo" :total="total" @change="onPageChangeHJZP" />
							</div>
						</div>
						<div v-if="infoType === '专家作品'" class="w-85%">
							<div class="flex items-center py-5">
								<div class="h-40px w-40px flex cursor-pointer items-center justify-center rounded-md"
									:style=" timeYS" @click="backInit">
									<div class="h-18px w-18px flex items-center justify-center rounded-50% bg-#fff">
										<span class="flex items-center -ml-2px" text="#0E9472">&lt;</span>
									</div>
								</div>
								<span class="pl-4 font-extrabold" text="#016738">{{ infoType }}</span>
							</div>
							<div v-if="typeList[2] && typeList[2].children" class="flex">
								<div v-for="item in typeList[2].children" text="#1D2128 16px"
									class="item-center w-100PX flex py-5px">
									<div class="w-100px cursor-pointer pt-2 text-center font-bold font-sans"
										:style="keyType === item.classify_name ? 'border-bottom:5px solid #35B389' : ''"
										@click="keyTypeClickAreaLeval(item.classify_name, '2')">
										{{ item .classify_name }}
									</div>
								</div>
							</div>
							<div v-if="ExpertworkList.length"
								grid="~ cols-[repeat(auto-fill,_minmax(200px,_1fr))] gap-10px" class="mt-15px">
								<div v-for="item in ExpertworkList" :key="item.id" calss="cursor-pointer"
									@click="toDetail(item.id, '专家作品')">
									<el-image class="h-200px w-100%" lazy fit="cover"
										:src="getImageAddress(item.cover_file_name)" alt="" />
									<div class="bg-#fff p-10px">
										<div class="cursor-pointer truncate hover:text-green-500">
											{{ item.title_name }}
										</div>
										<div class="flex justify-between">
											<span text="#AEAEB2 12px">
												{{ item.release_time.split(' ')[0] }}
											</span>
											<div class="flex">
												<img class="h-18px w-15px" :src="eyes" alt="">
												<span text="#AEAEB2 12px">{{ item.page_view_num }}</span>
											</div>
										</div>
									</div>
								</div>
							</div>
							<div v-else>
								<el-empty :image-size="200" />
							</div>
							<div class="mt-15px w-100% flex justify-end pr-20px">
								<PublicPagination :page-size="queryParams.page.rownumber"
									:page-num="queryParams.page.pageNo" :total="total" @change="onPageChangeHJZP" />
							</div>
						</div>
						<div v-if="infoType === '中医科普资料'" class="w-85%" />

						<div class="ml-20px w-15%">
							<div>
								<div class="h-10px flex items-center rounded-tl rounded-tr px-10px py-5px"
									:style=" timeYS" />
								<div class="rounded-bl rounded-br" border="2px solid #50bc8d">
									<div v-for="item in typeList" :key="item.id"
										class="flex cursor-pointer items-center p-2 pl-10"
										:style="infoType === item.classify_name ? infocss : ''"
										@click="typeClick(item.classify_name)">
										<!-- <i

                      class="ant-design:right-circle-outlined h-25px w-25px cursor-pointer text-#50bc8d"
                    /> -->
										<img v-if="infoType === item.classify_name" src="/img/right-f.png" alt=""
											class="pr-5px" style="flex-shrink: 0;width: 25px;height: 24px;">
										{{ item.classify_name }}
									</div>
									<!-- <div class="p-2 pl-10 cursor-pointer" :style="infoType === '获奖作品' ? infocss : ''"
                    @click="typeClick('获奖作品')">
                    <i v-if="infoType === '获奖作品'"
                      class="i-ri:arrow-right-circle-line cursor-pointer text-#50bc8d w-25px h-25px" />
                    获奖作品
                  </div> -->
								</div>
							</div>
							<div class="mt-20px">
								<div class="h-30px flex items-center rounded-tl rounded-tr px-10px py-5px"
									:style=" timeYS">
									<img src="/img/tj.png" alt="">
									<div class="pl-15px" text="#fff 16px">
										推荐
									</div>
								</div>
								<div class="rounded-bl rounded-br px-10px py-5px" border="2px solid #50bc8d">
									<div v-for="item in siderData" v-if="siderData && siderData.length" :key="item.id"
										@click="toDetail(item.id, infoType ? infoType : '推荐')">
										<el-image :src="getImageAddress(item.cover_file_name)" fit="cover" lazy alt=""
											class="h-124px w-100%" />
										<div class="cursor-pointer py-10px hover:text-green-500" text="14px">
											{{ item.title_name }}
										</div>
									</div>
									<div v-else>
										<el-empty :image-size="100" />
									</div>
								</div>
							</div>
						</div>
					</div>
				</CommonPageContainer>
			</div>
		</div>
	</div>
</template>

<style lang="scss">
	.image-slot {
		width: 100%;
		height: 150px;
		background-color: #f5f7fd;
		background-image: url('/img/placeholder.jpg');
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;

		// 实现一个无限循环转圈的loading动画
		.loader {
			display: inline-block;
			animation: loader 1s infinite linear;
			color: #fff;

			&::before {
				content: '';
				width: 100%;
				height: 100%;
				background-color: rgba($color: #000000, $alpha: 0.6);
				position: absolute;
				top: 0;
				left: 0;
			}
		}

		@keyframes loader {
			0% {
				transform: rotate(0deg);
			}

			50% {
				transform: rotate(180deg);
			}

			100% {
				transform: rotate(360deg);
			}
		}
	}
</style>